﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using FairyWorld.Models;
using System.Data.Entity;
using System.Net.Mail;

namespace FairyWorld.Controllers
{
    public class AccountController : Controller
    {
        SrcManager srcDB = new SrcManager();

        /// <summary>
        /// GET: /Account/LogOn 登陆
        /// </summary>
        /// <returns>登录视图</returns>
        public ActionResult LogOn()
        {
            HttpCookie htc = Request.Cookies["userLogin"];
            if (htc != null)
            {
                string userName = htc.Values["userName"].ToString();
                string userPwd = htc.Values["userPwd"].ToString();
                LogOnModel model = new LogOnModel();
                model.UserName = userName;
                model.Password = userPwd;
                return (LogOn(model, ""));
            }
            return View();
        }

        /// <summary>
        /// POST: /Account/LogOn
        /// </summary>
        /// <param name="model">登录用户信息</param>
        /// <param name="returnUrl">登录地址</param>
        /// <returns>如果验证通过，登陆地址视图</returns>
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                User user = srcDB.users.ToList().Find(u => u.email == model.UserName);
                if (user != null)
                {
                    if (user.password == model.Password)
                    {
                        this.HttpContext.Session["user"] = user.UserId;
                        if (model.RememberMe)
                        {
                            HttpCookie htc = new HttpCookie("userLogin");
                            htc.Values.Add("userName", model.UserName);
                            htc.Values.Add("userPwd", model.Password);
                            htc.Expires = DateTime.Now.AddDays(7);
                            Response.Cookies.Add(htc);
                        }
                        return RedirectToAction("Index", "Home");
                    }
                    else
                        ModelState.AddModelError("", "密码不正确，请更正错误并重试。");
                }
                else
                {
                    ModelState.AddModelError("", "该邮箱未被注册，请更正错误并重试。");
                }
            }
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        /// <summary>
        /// GET: /Account/LogOff 登出
        /// </summary>
        /// <returns>登录页面</returns>
        public ActionResult LogOff()
        {
            Response.Cookies["userLogin"].Expires = System.DateTime.Now.AddMonths(-1);
            this.HttpContext.Session["user"] = null;
            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// GET: /Account/Register 注册
        /// </summary>
        /// <returns>注册页面</returns>
        public ActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// POST: /Account/Register
        /// </summary>
        /// <param name="model">注册用户信息</param>
        /// <returns>新用户主页</returns>
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                User userEmail = srcDB.users.ToList().Find(u => u.email == model.Email);

                if (userEmail == null)
                {
                    User user = new User();
                    user.email = model.Email;
                    user.password = model.Password;
                    user.ConfirmPassword = model.ConfirmPassword;
                    user.username = model.UserName;
                    user.fold = new Fold();
                    user.iconUrl = "../../content/image/head/girlicon1.jpg";
                    srcDB.users.Add(user);
                    srcDB.SaveChanges();
                    this.HttpContext.Session["user"] = srcDB.users.ToList().Single(u => u.email == model.Email).UserId;
                    return RedirectToAction("Index", "Home");
                }
                else
                    ModelState.AddModelError("Email", "邮箱已经被注册！");
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        /// <summary>
        /// 发送忘记密码邮件
        /// </summary>
        /// <param name="email">邮箱地址</param>
        /// <returns>0</returns>
        [HttpPost]
        public int SendForgottenPassword(string email)
        {
            User user = srcDB.users.ToList().Find(u => u.email == email);
            if (user != null)
            {
                try
                {
                    MailMessage mail = new MailMessage();
                    mail.Subject = "Fairyworld找回密码";
                    mail.Body = "亲爱的"+user.username+"您的密码是"+user.password;
                    mail.From = new MailAddress("fairylandnote@gmail.com", "fairyworld资料管理平台");
                    mail.To.Add(email);
                    // send the e-mail
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com"; // SMTP Server Address
                    smtp.Port = 587;
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new System.Net.NetworkCredential("fairylandnote@gmail.com", "fairyland123");
                    smtp.EnableSsl = true;
                    smtp.Send(mail);
                    return 1;
                }
                catch (Exception e)
                {
                    throw new ApplicationException(e.Message);
                }
            }
            return 0;
        }

        /// <summary>
        /// 发送建议反馈
        /// </summary>
        /// <param name="advise">反馈信息</param>
        /// <returns>是否反馈</returns>
        [HttpPost]
        public int SendAdvise(string advise)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.Subject = "Fairyworld建议反馈";
                mail.Body = advise;
                mail.From = new MailAddress("fairylandnote@gmail.com", "fairyworld资料管理平台");
                mail.To.Add("fairylandnote@gmail.com");
                // send the e-mail
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com"; // SMTP Server Address
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential("fairylandnote@gmail.com", "fairyland123");
                smtp.EnableSsl = true;
                smtp.Send(mail);
                return 1;
            }
            catch (Exception e)
            {
                return 0;
                throw new ApplicationException(e.Message);
            }
        }

        /// <summary>
        /// GET: /Account/Contact 联系我们
        /// </summary>
        /// <returns>联系视图</returns>
        public ActionResult Contact()
        {
            return View();
        }

        /// <summary>
        /// GET: /Account/About 关于我们
        /// </summary>
        /// <returns>关于视图</returns>
        public ActionResult About()
        {
            return View();
        }
    }
}
